 (function() {
     /**
      * 送入【格林尼治标准时间】
      * 根据format格式化成【当地时间】的字符串
      */
     angular.module('webApp')
         .directive('datetimepicker', ['dataService', '$compile', '$timeout', 'moment',
             function(dataService, $compile, $timeout, moment) {
                 return {
                     restrict: 'EA',
                     require: 'ngModel',
                     scope: {
                         ngModel: "=",
                         minDate: '@',
                         maxDate: '@',
                         type: "@",
                         callback: "&",
                     },
                     link: function(scope, element, attr, ctrl) {
                         function onpicked(dp) {
                             var date = dp.cal.getNewDateStr();
                             $timeout(function() {
                                 ctrl.$setViewValue(date);
                             });
                             if (scope.callback) {
                                 scope.callback({ date: date });
                             }
                         }

                         scope.type = scope.type ? scope.type : "yyyy-MM-dd HH:mm:ss";
                         element.val(ctrl.$viewValue);
                         element.addClass("Wdate");
                         var lang = window.localStorage.lang || 'zh-cn';
                         element.bind('click', function() {
                             // console.log("minDate-----", scope.minDate);
                             WdatePicker({
                                 el: this,
                                 skin: 'twoer',
                                 lang: lang,
                                 onpicked: onpicked,
                                 dateFmt: scope.type,
                                 minDate: scope.minDate,
                                 maxDate: scope.maxDate,
                             });
                         });
                     }
                 };
             }
         ])
         .run(["$templateCache", "dataService",
             function($templateCache, dataService) {
                 var tplName = "views/directives.newtimeslot.html";
                 dataService.tpl(tplName).then(function(html) {
                     $templateCache.put(tplName, html);
                 });
             }
         ])
         .directive('newdatetimepickerlist', ['dataService', '$compile', '$timeout', 'moment',
             function(dataService, $compile, $timeout, moment) {
                 return {
                     restrict: 'EA',
                     require: 'ngModel',
                     template: '<div><div ng-show="periocd.length"  style="text-align: center;" id="div1" ></div><div>注：点击日期进行时段设置;</div> <div ng-if="!periocd.length">没有找到设置的日期数据，请重新执行发布！</div></div>',
                     scope: {
                         ngModel: "=",
                         minDate: '@',
                         maxDate: '@',
                         disary: "@",
                         type: "@"
                     },
                     controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'helper', function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, helper) {

                         $scope.init = function(schemaid, periodtstlid) {
                             return dataService.periodsGet({
                                 page_size: 100,
                                 query: { res_item_id: $scope.ngModel }
                             }).then(function(re1) {
                                 if (re1.periods.length > 0) {
                                     $scope.per = re1.periods;
                                     //sortBy 根据source_at 进行排序
                                     $scope.periocd = _.sortBy($scope.per, 'source_at');
                                     console.error("查询出数据", $scope.periocd);
                                     $scope.num = $scope.periocd.length;
                                     var source = $scope.periocd[0].source_at;
                                     // $scope.minDate = moment().format('YYYY-MM-DD');
                                     if (moment(moment().format('YYYY-MM-DD')).isBefore(source)) {
                                         $scope.minDate = source;
                                     } else {
                                         $scope.minDate = moment().format('YYYY-MM-DD');
                                     }
                                     $scope.maxDate = $scope.periocd[$scope.num - 1].source_at;
                                     jinyong();

                                     return $scope.periocd;

                                 }
                             })
                         }

                         $scope.click = function() {
                             $scope.inittimeslot().then(showPop);
                             $scope.title = $scope.checkdate + "每个时段设置";
                         }

                         $scope.inittimeslot = function() {
                             var query = { res_item_id: $scope.ngModel, periods_id: $scope.periods_id };
                             return dataService.periodsGet({ query: query }).then(function(re1) {
                                 if (re1.periods) {
                                     $scope.deskData = re1.periods[0];
                                     $scope.deskData.timeslots = _.sortBy($scope.deskData.timeslots, 'timeslot_no');
                                     console.error($scope.deskData);
                                 }
                             })
                         }
                         //删除
                         $scope.deletetime = function(timeslots_id) {
                             helper.myConfirm("确认删除吗？", function() {
                                 var data = { periods_id: $scope.periods_id, res_item_id: $scope.ngModel, timeslots: JSON.stringify({ timeslots: [{ timeslots_id: timeslots_id }] }) };
                                 dataService.periodsDelete(data).then(function(da) {
                                     $scope.inittimeslot();
                                 });
                             })
                         }
                         /**
                          * 获取时间段日的日期数组
                          */
                         function getDate(datestr) {  
                             var temp = datestr.split("-");  
                             var date = new Date(temp[0], temp[1], temp[2]);  
                             return date;
                         }

                         function getDates(start, end) {  
                             var startTime = new Date(start);
                             var endTime = new Date(end);
                             if(endTime.getTime() < startTime.getTime()){
                                  
                             }
                             var datas = [];
                             while ((endTime.getTime() - startTime.getTime()) >= 0) { 
                                 var year = startTime.getFullYear();  
                                 var getMonth = startTime.getMonth() +1 ;
                                 var month = getMonth.toString().length == 1 ? "0" + getMonth.toString() : getMonth;  
                                 var day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();   
                                 datas.push(year + "-" + month + "-" + day);
                                 startTime.setDate(startTime.getDate() + 1);
                             }
                             return datas;
                         }


                         //禁用日期
                         function jinyong() {
                             var oiddata = [];
                             _.map($scope.periocd, function(da, ke) {
                                 if (da.source_at >= $scope.minDate) {
                                     oiddata.push(da.source_at);
                                 }
                             });

                             var disarys = getDates($scope.minDate, $scope.maxDate);
                             if (disarys) {

                                $scope.disarys = _.difference(disarys, oiddata);
                             }

                             console.error("展示数据/////",$scope.periocd);
                             console.error("禁用数据/////",$scope.disarys);
                         }


                         function showPop() {
                             $.alert({
                                 backdrop: 'static',
                                 keyboard: true,
                                 title: '{{title | translate}}',
                                 body: $templateCache.get("views/directives.newtimeslot.html"),
                                 okBtn: '{{"保存" | translate}}',
                                 closeBtn: true,
                                 transition: true,
                                 width: 'normal',
                                 // height: 300,
                                 // hasfoot: false,
                                 show: function(e) {
                                     $compile($(e.currentTarget).contents())($scope);
                                     return true;
                                 },
                                 okHide: function(e) {
                                     for (var i = $scope.deskData.timeslots.length - 1; i >= 0; i--) {
                                         if ($scope.deskData.timeslots[i].start == '0' || $scope.deskData.timeslots[i].end == '0') {
                                             helper.myAlert("时间填写不能为空!");
                                             return false;
                                         }
                                         if ($scope.deskData.timeslots[i].start == $scope.deskData.timeslots[i].end) {
                                             helper.myAlert("开始时间不能和结束时间相同!" + $scope.deskData.timeslots[i].start + "和" + $scope.deskData.timeslots[i].end);
                                             return false;
                                         }
                                     }

                                     $scope.saveData();
                                 },
                             });
                         }


                         $scope.Testing = function(key) {
                             _.map($scope.deskData, function(da, ke) {
                                 if (key == ke) {
                                     if (da.start == da.end) {
                                         helper.myAlert("开始时间不能和结束时间相同!");
                                         da.end = '0';
                                     }
                                 }
                             });
                         }

                         $scope.saveData = function() {
                             var da = clone($scope.deskData);
                             da.timeslots = JSON.stringify({ timeslots: da.timeslots });
                             dataService.periodsUpdate(da).then(function(r) {

                             })
                         }

                     }],
                     link: function(scope, element, attr, ctrl) {
                         function onpicked(dp) {
                             scope.checkdate = dp.cal.getNewDateStr();
                             _.map(scope.periocd, function(da, ke) {
                                 if (da.source_at == scope.checkdate) {
                                     scope.periods_id = da.periods_id;
                                     scope.click();
                                 }
                             });
                         }

                         $timeout(function() {
                             scope.init().then(function() {
                                 scope.type = scope.type ? scope.type : "yyyy-MM-dd";
                                 var lang = window.localStorage.lang || 'zh-cn';
                                 if (scope.periocd && scope.minDate && scope.maxDate) {
                                     WdatePicker({
                                         eCont: 'div1',
                                         el: this,
                                         skin: 'twoer',
                                         lang: lang,
                                         onpicked: onpicked,
                                         dateFmt: scope.type,
                                         minDate: scope.minDate,
                                         maxDate: scope.maxDate,
                                         // disabledDays: scope.disary,
                                         disabledDates: scope.disarys
                                     });
                                 }

                             });
                         });


                     }
                 };
             }
         ])
         .directive('datetimepickerlist', ['dataService', '$compile', '$timeout', 'moment',
             function(dataService, $compile, $timeout, moment) {
                 return {
                     restrict: 'EA',
                     require: 'ngModel',
                     template: '<div><div style="text-align: center;" id="div1" ></div><div>注：点击日期进行时段设置;</div> <div ng-if="!periocd">没有生成数据</div></div>',
                     scope: {
                         ngModel: "=",
                         minDate: '@',
                         maxDate: '@',
                         disary: "@",
                         type: "@"
                     },
                     controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'helper', function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, helper) {

                         $scope.init = function(schemaid, periodtstlid) {
                             return dataService.periodGet({
                                 page_size: 100,
                                 query: { schema_id: $scope.ngModel }
                             }).then(function(re1) {
                                 if (re1.periods.length > 0) {
                                     $scope.per = re1.periods;
                                     $scope.periocd = _.sortBy($scope.per, 'source_at');
                                     console.error("$scope.periocd", $scope.periocd);
                                     $scope.num = $scope.periocd.length;
                                     var source = $scope.periocd[0].source_at;
                                     // $scope.minDate = moment().format('YYYY-MM-DD');
                                     if (moment(moment().format('YYYY-MM-DD')).isBefore(source)) {
                                         $scope.minDate = source;
                                     } else {
                                         $scope.minDate = moment().format('YYYY-MM-DD');
                                     }
                                     $scope.maxDate = $scope.periocd[$scope.num - 1].source_at;
                                     jinyong();
                                     return $scope.periocd;
                                 }
                             })
                         }

                         $scope.click = function() {
                             $scope.inittimeslot().then(showPop);
                             $scope.title = $scope.checkdate + "每个时段设置";
                         }


                         /**
                          * 获取时间段日的日期数组
                          */
                         function getDate(datestr) {  
                             var temp = datestr.split("-");  
                             var date = new Date(temp[0], temp[1], temp[2]);  
                             return date;
                         }

                         function getDates(start, end) {  
                             var startTime = getDate(start);
                             var endTime = getDate(end);
                             var datas = [];
                             while ((endTime.getTime() - startTime.getTime()) >= 0) {  
                                 var year = startTime.getFullYear();  
                                 var month = startTime.getMonth().toString().length == 1 ? "0" + startTime.getMonth().toString() : startTime.getMonth();  
                                 var day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();   
                                 datas.push(year + "-" + month + "-" + day);
                                 startTime.setDate(startTime.getDate() + 1);
                             }
                             return datas;
                         }

                         //禁用日期
                         function jinyong() {
                             var oiddata = [];
                             _.map($scope.periocd, function(da, ke) {
                                 if (da.source_at >= $scope.minDate) {
                                     oiddata.push(da.source_at);
                                 }
                             });
                             var disarys = getDates($scope.minDate, $scope.maxDate);
                             $scope.disarys = _.difference(disarys, oiddata);
                             console.error(" $scope.disarys", $scope.disarys);
                         }


                         function showPop() {
                             $.alert({
                                 backdrop: 'static',
                                 keyboard: true,
                                 title: '{{title | translate}}',
                                 body: $templateCache.get("views/directives.timeslot.html"),
                                 okBtn: '{{"保存" | translate}}',
                                 closeBtn: true,
                                 transition: true,
                                 width: 'normal',
                                 // height: 300,
                                 // hasfoot: false,
                                 show: function(e) {
                                     $compile($(e.currentTarget).contents())($scope);
                                     return true;
                                 },
                                 okHide: function(e) {
                                     var istype;
                                     _.map($scope.deskData, function(da, k) {
                                         if (da.start == '0' || da.end == '0') {
                                             helper.myAlert("时间填写不能为空!");
                                             istype = 1;
                                         }
                                         if (da.start == da.end) {
                                             helper.myAlert("开始时间不能和结束时间相同!" + da.start + "和" + da.end);
                                             istype = 1;
                                         }
                                     });
                                     if (istype) {
                                         return false;
                                     } else {
                                         $scope.saveData();
                                     }
                                 },
                             });
                         }

                         $scope.inittimeslot = function() {
                             var query = { schema_id: $scope.ngModel, period_id: $scope.periodid };
                             return dataService.timeslotGet({ query: query }).then(function(re1) {
                                 if (re1.timeslots) {
                                     $scope.time = re1.timeslots;
                                     $scope.deskData = _.sortBy($scope.time, 'timeslot_no');
                                 }
                             })
                         }
                         $scope.Testing = function(key) {
                             _.map($scope.deskData, function(da, ke) {
                                 if (key == ke) {
                                     if (da.start == da.end) {
                                         helper.myAlert("开始时间不能和结束时间相同!");
                                         da.end = '0';
                                     }
                                 }
                             });
                         }

                         $scope.saveData = function() {
                             async.mapValues($scope.deskData, function(data, key, callback) {
                                 data.schema_id = $scope.ngModel;
                                 data.period_id = $scope.periodid;
                                 dataService.timeslotUpdate(data).then(function(r) {
                                     callback(null);
                                 })
                             }, function(e, r) {
                                 // helper.myAlert("success", null, null, function() {
                                 //     rmAlert();
                                 // });
                             });
                         }

                     }],
                     link: function(scope, element, attr, ctrl) {
                         function onpicked(dp) {
                             scope.checkdate = dp.cal.getNewDateStr();
                             _.map(scope.periocd, function(da, ke) {
                                 if (da.source_at == scope.checkdate) {
                                     scope.periodid = da.period_id;
                                     scope.click();
                                 }
                             });
                         }
                         scope.init().then(function() {
                             scope.type = scope.type ? scope.type : "yyyy-MM-dd";
                             var lang = window.localStorage.lang || 'zh-cn';
                             if (scope.periocd) {
                                 WdatePicker({
                                     eCont: 'div1',
                                     el: this,
                                     skin: 'twoer',
                                     lang: lang,
                                     onpicked: onpicked,
                                     dateFmt: scope.type,
                                     minDate: scope.minDate,
                                     maxDate: scope.maxDate,
                                     // disabledDays: scope.disary,
                                     disabledDates: scope.disarys
                                 });
                             }

                         });



                     }
                 };
             }
         ]);
 })();